package sg.edu.nus.iss.phoenix.authenticate.service;

import sg.edu.nus.iss.phoenix.authenticate.dao.RoleDao;
import sg.edu.nus.iss.phoenix.authenticate.dao.UserDao;
import sg.edu.nus.iss.phoenix.authenticate.entity.Role;
import sg.edu.nus.iss.phoenix.authenticate.entity.User;
import sg.edu.nus.iss.phoenix.core.dao.DAOFactoryImpl;
import sg.edu.nus.iss.phoenix.core.exceptions.NotFoundException;

import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class AuthenticateService {

    private static final Logger logger =
            Logger.getLogger(AuthenticateService.class.getName());

    DAOFactoryImpl factory;
    UserDao udao;
    RoleDao rdao;

    /**
     * constructor
     */
    public AuthenticateService() {
        super();
        // TODO Auto-generated constructor stub
        factory = new DAOFactoryImpl();
        udao = factory.getUserDAO();
        rdao = factory.getRoleDAO();

    }

    /**
     * Validate user name, password and return the logged in user
     *
     * @param toAuth
     * @return authenticated user if success, null if fail
     */
    public User validateUserIdPassword(final User toAuth) {
        User found = null;
        try {
            found = udao.searchMatching(toAuth.getId());
            if (!found.getPassword().equals(toAuth.getPassword())) {
                return null;
            }
        } catch (SQLException ex) {
            logger.log(Level.SEVERE, "user searchMatching", ex);
            return (null);
        }
        if (null == found)
            return (null);

        //Populate the roles
        try {
            for (Role r : found.getRoles()) {
                Role _role = rdao.searchMatching(r.getRole());
                //Should we do something with roles that are without access privilege?
                if (null != _role)
                    r.setAccessPrivilege(_role.getAccessPrivilege());
            }
        } catch (SQLException ex) {
            logger.log(Level.SEVERE, "user searchMatching", ex);
        }

        return (found);
    }

    /**
     * get user that have specific role
     *
     * @param user
     * @return user
     */
    public User evaluateAccessPreviledge(User user) {
        try {
            Role role = rdao.getObject(user.getRoles().get(0).getRole());
            return user;
        } catch (NotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return user;
    }

}
